<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';

import { computed, h, onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Modal as AModal, Button, Form, Input, message, Select } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { registerApi } from '#/api/core/auth';
import {
  createInvitationCodeApi,
  deleteUserApi,
  getUserDevicesApi,
  getUserListApi,
  resetInvitationCodeApi,
  setInvitationCodeApi,
  unbindDeviceApi,
  updateUserStatusApi,
} from '#/api/core/user-management';

// 添加表格引用
const gridRef = ref<VxeGridInstance>();

interface UserData {
  id: number;
  username: string;
  token_count: string;
  create_time: string;
  status: string;
  user_type: string;
  current_page: number;
  total_page: number;
  parent_username: string;
}

// 在 interface UserData 后添加设备列表接口
interface DeviceInfo {
  user_app_id: number;
  app_name: string;
  devices_no_list: string[];
  devices_count: number;
}

// 存储表格数据
const tableData = ref<UserData[]>([]);

// 添加设备列表的 ref
const deviceList = ref<DeviceInfo[]>([]);

// 添加分页相关的 ref
const currentPage = ref(1);
const totalPage = ref(0);

// 添加邀请码相关的状态
const currentInvitationCode = ref('');
const currentUserForCode = ref<null | UserData>(null);

// 添加当前用户名的 ref
const currentUsername = ref('');

// 添加搜索表单数据
const searchForm = ref({
  username: '',
  status: undefined,
});

// 将 gridOptions 修改为计算属性
const gridOptions = computed<VxeGridProps<UserData>>(() => ({
  columns: [
    { field: 'id', title: 'ID' },
    { field: 'username', title: '用户名' },
    { field: 'parent_username', title: '上级用户' },
    { field: 'token_count', title: 'Token 数量' },
    {
      field: 'status',
      title: '状态',
      formatter: ({ cellValue }) => cellValue,
    },
    { field: 'user_type', title: '用户类型' },
    { field: 'invitation_code', title: '邀请码' },
    {
      field: 'create_time',
      title: '创建时间',
      width: 180,
      formatter: ({ cellValue }) => {
        if (!cellValue) return '';
        return new Date(cellValue).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        });
      },
    },
    {
      field: 'operate',
      title: '操作',
      width: 500, // 增加宽度以适应新按钮
      slots: {
        default: ({ row }) => {
          return [
            h(
              Button,
              {
                type: 'link',
                onClick: () => handleStatusChange(row),
              },
              () => (row.status === '正常' ? '禁用' : '启用'),
            ),
            h(
              Button,
              {
                type: 'link',
                onClick: () => handleViewDevices(row),
              },
              () => '查看设备',
            ),
            h(
              Button,
              {
                type: 'link',
                danger: true,
                onClick: () => handleDeleteUser(row),
              },
              () => '删除',
            ),
            h(
              Button,
              {
                type: 'link',
                onClick: () => handleSetCode(row),
              },
              () => '设置邀请码',
            ),
            h(
              Button,
              {
                type: 'link',
                onClick: () => handleResetCode(row),
              },
              () => '重置邀请码',
            ),
          ];
        },
      },
    },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
  sortConfig: {
    multiple: true,
  },
}));

const gridEvents: VxeGridListeners<UserData> = {
  pageChange: ({ currentPage: newPage }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 修改加载数据方法
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params = {
      username: searchForm.value.username,
      status: searchForm.value.status ?? 0,
      current_page: currentPage.value,
    };
    const data = await getUserListApi(params);

    if (Array.isArray(data) && data.length > 0) {
      tableData.value = data;
      const total_page = data[0]?.total_page || 0;
      totalPage.value = total_page;

      gridApi.setGridOptions({
        data: tableData.value,
        pagerConfig: {
          ...gridOptions.value.pagerConfig,
          total: total_page * 10,
          currentPage: currentPage.value,
        },
      });
    } else {
      tableData.value = [];
    }
  } catch {
    message.error('获取用户列表失败');
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

onMounted(() => {
  loadData();
});

const showBorder = gridApi.useStore((state) => state.gridOptions?.border);
const showStripe = gridApi.useStore((state) => state.gridOptions?.stripe);

function changeBorder() {
  gridApi.setGridOptions({
    border: !showBorder.value,
  });
}

function changeStripe() {
  gridApi.setGridOptions({
    stripe: !showStripe.value,
  });
}

// 注册表单数据
const registerFormData = ref({
  username: '',
  password: '',
});

// 注册模态框
const [Modal, modalApi] = useVbenModal({
  title: '用户注册',
  width: '500px',
  async onConfirm() {
    try {
      await registerApi(registerFormData.value);
      message.success('注册成功');
      modalApi.close();
      loadData();
    } catch (error) {
      message.error('注册失败');
      console.error('Registration error:', error);
    }
  },
});

// 打开注册模态框
function registerUser() {
  registerFormData.value = {
    username: '',
    password: '',
  };
  modalApi.open();
}

// 修改删除用户方法
async function handleDeleteUser(row: UserData) {
  try {
    await new Promise((resolve, reject) => {
      AModal.confirm({
        title: '确认删除',
        content: '确定要删除该用户吗？',
        onOk: () => resolve(true),
        onCancel: () => reject(new Error('用户取消删除')),
      });
    });

    await deleteUserApi(row.id);
    message.success('删除成功');
    loadData(); // 重新加载数据
  } catch (error) {
    if (error instanceof Error && error.message !== '用户取消删除') {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  }
}

// 修改状态切换处理方法
async function handleStatusChange(row: UserData) {
  try {
    const newStatus = row.status === '正常' ? 0 : 1;
    await updateUserStatusApi(row.id, newStatus);
    row.status = newStatus === 1 ? '正常' : '关闭';
    message.success('状态更新成功');
  } catch (error) {
    console.error('更新状态失败:', error);
    message.error('更新状态失败');
  }
}

// 修改设备列表的渲染部分
const deviceGridOptions = computed<VxeGridProps<DeviceInfo>>(() => ({
  columns: [
    {
      field: 'user_app_id',
      title: '应用ID',
      width: 100,
      align: 'center',
    },
    {
      field: 'app_name',
      title: '应用名称',
      width: 300,
    },
    {
      field: 'devices_no_list',
      title: '设备列表',
      minWidth: 500,
      slots: {
        default: ({ row }) => {
          return h(
            'div',
            { class: 'devices-list' },
            row.devices_no_list.map((device: string) =>
              h(
                'div',
                {
                  class: 'device-item',
                },
                [
                  h(
                    'span',
                    {
                      class: 'device-text',
                      onClick: () => copyToClipboard(device),
                      title: '点击复制',
                    },
                    device,
                  ),
                  h(
                    Button,
                    {
                      type: 'primary',
                      danger: true,
                      size: 'small',
                      class: 'unbind-btn',
                      onClick: () =>
                        handleUnbind(currentUsername.value, device),
                    },
                    '解除绑定',
                  ),
                ],
              ),
            ),
          );
        },
      },
    },
    {
      field: 'devices_count',
      title: '设备数量',
      width: 100,
      align: 'center',
    },
  ],
  border: true,
  stripe: true,
  height: 800,
  width: 1200,
  showOverflow: true,
  scrollY: { enabled: true },
  scrollX: { enabled: true },
  emptyText: '暂无设备数据',
}));

// 建设备列表的 Grid - 移到前面
const [DeviceGrid, deviceGridApi] = useVbenVxeGrid({
  gridOptions: deviceGridOptions.value,
});

// 添加复制函数
function copyToClipboard(text: string) {
  try {
    // 创建临时文本区域
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.append(textArea);
    textArea.select();

    // 尝试使用新的 API
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          message.success('设备号已复制');
        })
        .catch(() => {
          // 如果 clipboard API 失败，使用传统方法
          document.execCommand('copy');
          message.success('设备号已复制');
        });
    } else {
      // 在不支持 clipboard API 的环境中使用传统方法
      document.execCommand('copy');
      message.success('设备号已复制');
    }

    // 清理临时元素
    textArea.remove();
  } catch (error) {
    console.error('复制失败:', error);
    message.error('复制失败');
  }
}

// 添加解除绑定的处理函数
async function handleUnbind(username: string, deviceNo: string) {
  try {
    await new Promise((resolve, reject) => {
      AModal.confirm({
        title: '确认解绑',
        content: '确定要解除此设备的绑定吗？',
        onOk: () => resolve(true),
        onCancel: () => reject(new Error('用户取消解绑')),
      });
    });

    await unbindDeviceApi({ username, devices_no: deviceNo });
    message.success('解绑成功');

    // 重新加载设备列表
    const response = await getUserDevicesApi({ username });
    deviceList.value = response;
    deviceGridApi.setGridOptions({
      data: response,
    });
  } catch (error) {
    if (error instanceof Error && error.message !== '用户取消解绑') {
      console.error('解绑设备失败:', error);
      message.error('解绑设备失败');
    }
  }
}

// 修改设备列表模态框的配置
const [DeviceModal, deviceModalApi] = useVbenModal({
  title: '用户设备列表',
  class: 'device-modal',
});

// 修改查看设备处理函数
async function handleViewDevices(row: UserData) {
  try {
    currentUsername.value = row.username;
    const response = await getUserDevicesApi({ username: row.username });
    deviceList.value = response;

    deviceGridApi.setGridOptions({
      data: response,
    });

    deviceModalApi.open();
  } catch {
    message.error('获取设备列表失败');
  }
}

// 设置邀请码模态框
const [InvitationCodeModal, invitationCodeModalApi] = useVbenModal({
  title: '设置邀请码',
  width: '500px',
  async onConfirm() {
    if (!currentUserForCode.value || !currentInvitationCode.value) return;

    try {
      await setInvitationCodeApi({
        username: currentUserForCode.value.username,
        invitation_code: currentInvitationCode.value,
      });
      message.success('设置邀请码成功');
      invitationCodeModalApi.close();
      loadData();
    } catch (error) {
      message.error('设置邀请码失败');
      console.error('设置邀请码错误:', error);
    }
  },
});

// 修改创建邀请码的处理函数
async function handleCreateCode() {
  try {
    const response = await createInvitationCodeApi();
    currentInvitationCode.value = response.code;
    message.success('创建邀请码成功');
  } catch {
    message.error('创建邀请码失败');
  }
}

// 打开设置邀请码模态框
function handleSetCode(row: UserData) {
  currentUserForCode.value = row;
  currentInvitationCode.value = '';
  invitationCodeModalApi.open();
}

// 重置邀请码
async function handleResetCode(row: UserData) {
  try {
    await new Promise((resolve, reject) => {
      AModal.confirm({
        title: '确认重置',
        content: '确定要重置该用户的邀请码吗？',
        onOk: () => resolve(true),
        onCancel: () => reject(new Error('用户取消重置')),
      });
    });

    await resetInvitationCodeApi(row.username);
    message.success('重置邀请码成功');
    loadData();
  } catch (error) {
    if (error instanceof Error && error.message !== '用户取消重置') {
      console.error('重置邀请码失败:', error);
      message.error('重置邀请码失败');
    }
  }
}

// 添加搜索处理函数
function handleSearch() {
  currentPage.value = 1;
  loadData();
}

// 添加重置搜索条件函数
function handleReset() {
  searchForm.value = {
    username: '',
    status: undefined,
  };
  currentPage.value = 1;
  loadData();
}
</script>

<template>
  <div class="vp-raw w-full">
    <Modal>
      <Form :model="registerFormData" layout="vertical">
        <Form.Item label="用户名" name="username">
          <Input
            v-model:value="registerFormData.username"
            placeholder="请输入用户名"
          />
        </Form.Item>
        <Form.Item label="密码" name="password">
          <Input.Password
            v-model:value="registerFormData.password"
            placeholder="请输入密码"
          />
        </Form.Item>
      </Form>
    </Modal>

    <!-- 修改设备列表模态框 -->
    <DeviceModal>
      <div class="device-list">
        <DeviceGrid />
      </div>
    </DeviceModal>

    <Grid ref="gridRef">
      <template #toolbar-tools>
        <div class="flex items-center gap-4 mb-4">
          <Form 
            layout="inline" 
            :model="searchForm"
            class="flex-1"
          >
            <Form.Item label="用户名">
              <Input
                v-model:value="searchForm.username"
                placeholder="请输入用户名"
                allowClear
              />
            </Form.Item>
            <Form.Item label="状态">
              <Select
                v-model:value="searchForm.status"
                placeholder="请选择状态"
                allowClear
                style="width: 120px"
              >
                <Select.Option :value="1">正常</Select.Option>
                <Select.Option :value="0">关闭</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" @click="handleSearch">搜索</Button>
              <Button class="ml-2" @click="handleReset">重置</Button>
            </Form.Item>
          </Form>
          <Button class="mr-2" type="primary" @click="registerUser">
            用户注册
          </Button>
          <Button class="mr-2" type="primary" @click="changeBorder">
            {{ showBorder ? '隐藏' : '显示' }}边框
          </Button>
          <Button class="mr-2" type="primary" @click="changeStripe">
            {{ showStripe ? '隐藏' : '显示' }}斑马纹
          </Button>
        </div>
      </template>
    </Grid>

    <!-- 添加邀请码设置模态框 -->
    <InvitationCodeModal>
      <div class="invitation-code-modal">
        <Input
          v-model:value="currentInvitationCode"
          class="mb-4"
          placeholder="请输入邀请码"
        />
        <div class="flex gap-4">
          <Button type="primary" @click="handleCreateCode"> 创建邀请码 </Button>
        </div>
      </div>
    </InvitationCodeModal>
  </div>
</template>

<style>
.device-list {
  width: 100%;
  padding: 12px;
}

.device-modal {
  width: 1200px;
  height: 1000px;
}

.devices-list {
  padding: 4px;
}

.device-text {
  color: #000;
}

.device-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  margin: 4px 0;
  font-family: monospace;
  word-break: break-all;
  cursor: pointer;
  background-color: #f5f5f5;
  border-radius: 4px;
  transition: all 0.3s;
}

.device-item:hover {
  background-color: #e6f7ff;
}

.copy-hint {
  margin-left: 8px;
  font-size: 12px;
  color: #1890ff;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: bold;
  background-color: #f7f7f7;
}

:deep(.ant-modal-body) {
  padding: 0;
}

:deep(.ant-modal) {
  max-width: 95vw;
}

:deep(.ant-modal-content) {
  width: 100%;
}

:deep(.vxe-table--main-wrapper) {
  width: 100%;
}

.invitation-code-modal {
  padding: 20px;
}

.search-form {
  margin-bottom: 16px;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}
</style>
